package com.basic.bio.chat.groupchat;

import java.io.*;
import java.net.Socket;


/**
 * @Description:
 * @Date: 2024-03-28 19:39
 * @Author: wz
 **/
public class ServerReceiveThread extends Thread{

    private Socket socket;

    public ServerReceiveThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        System.out.println("服务端开始收消息咯。。。");
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String msg;
            while ((msg = reader.readLine())!=null){
                System.out.println("收到客户端发来的消息："+msg);
                for (Socket s : Server.socketList) {
                    if(s.equals(socket)){
                        continue;
                    }
                    System.out.println("开始分发");
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                    writer.write(msg);
                    writer.newLine();
                    writer.flush();
                    System.out.println("分发给其它客户端的消息："+msg);
                }
            }

        } catch (IOException e) {
            System.out.println("服务下线了");
            Server.socketList.remove(socket);
            e.printStackTrace();
        }
    }
}
